const Book = require("../models/Book");
const db = require("../db");
const _ = require("lodash");
const { debug } = require("../utils/constant");

function isExists(book) {
  const { title, author, publisher } = book;
  // 检查这3项
  const sql = `select * from book where title='${title}' and author='${author}' and publisher='${publisher}'`;
  return db.queryOne(sql);
}

async function removeBook(book) {
  //1. 检查 对象是否为空
  if (book) {
    //2. 删除 服务端存储的物理文件
    book.reset();
    // 个人感觉这一步没必要，文件没必要重复传，可以单独做1个删除功能
    //3. 删除数据库中数据
    const removeBookSql = `delete from book where fileName='${book.fileName}'`;
    const removeContentsSql = `delete from contents where filename='${book.fileName}'`;
    await db.querySql(removeBookSql);
    await db.querySql(removeContentsSql);
  }
}

async function insertContents(book) {
  const contents = book.getContents();
  // console.log("contents", contents);
  if (contents && contents.length > 0) {
    for (let i = 0; i < contents.length; i++) {
      const content = contents[i];
      const _content = _.pick(content, [
        "fileName",
        "id",
        "href",
        "order",
        "level",
        "label",
        "text",
        "pid",
        "navId",
      ]);
      // console.log("content", _content);
      await db.insert(_content, "contents");
    }
  }
}

function insertBook(book) {
  return new Promise(async (resolve, reject) => {
    try {
      // 检查参数
      if (book instanceof Book) {
        //判断电子书是否存在
        const result = await isExists(book);
        // const result = false;
        if (result) {
          await removeBook(book); // 如果存在则删除
          reject(new Error("电子书已存在"));
        } else {
          //正常，可以新增
          await db.insert(book.toDB(), "book"); //对象，表名；对象保存入表名
          await insertContents(book); // 电子书目录，保存进数据库
          resolve();
        }
      } else {
        reject(new Error("添加的图书对象不合法"));
      }
    } catch (e) {
      reject(e);
    }
  });
}
// 从数据库 取得 book
function getBook(fileName) {
  return new Promise(async (resolve, reject) => {
    const bookSql = `select * from book where fileName='${fileName}'`;
    const contentsSql = `select * from contents where fileName='${fileName}' order by \`order\``;
    const book = await db.queryOne(bookSql);
    const contents = await db.querySql(contentsSql);
    if (book) {
      book.cover = Book.genCoverUrl(book); //返回url 格式
      book.coverPath = book.cover;
      book.contentsTree = Book.genContentsTree(contents);
      resolve({ book });
    } else {
      reject(new Error("电子书不存在"));
    }
  });
}

function updateBook(book) {
  return new Promise(async (resolve, reject) => {
    try {
      // 检查参数
      if (book instanceof Book) {
        const model = book.toDB();
        await db.update(model, "book", `where fileName='${book.fileName}'`); //对象，表名；对象保存入表名
        resolve();
      }
    } catch (e) {
      reject(e);
    }
  });
}

async function getCategory() {
  const sql = `select * from category order by category`;
  const result = await db.querySql(sql);
  const categoryList = [];
  result.forEach((element) => {
    categoryList.push({
      label: element.categoryText,
      value: element.category,
      num: element.num,
    });
  });
  return categoryList;
}

async function listBook(query) {
  debug && console.log("listBook", query);
  //解构出参数
  const { title, author, category, page = 1, pageSize = 20 } = query;
  const offset = (page - 1) * pageSize;
  let bookSql = `select * from book`;
  let where = `where 1=1`;
  category && (where = where + ` and category=${category}`);
  title && (where = where + ` and title like '%${title}%'`);
  author && (where = where + ` and author like '%${author}%'`);
  bookSql = `${bookSql} ${where} limit ${pageSize} offset ${offset}`;
  const list = await db.querySql(bookSql);
  return { list }; // async 函数中，返回对象会自动转成Promise对象
}

module.exports = {
  insertBook,
  getBook,
  updateBook,
  getCategory,
  listBook,
};
